package com.sincetimes.game.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Http访问工作
 */
public class HttpUtil {
	public static Log logger = LogFactory.getLog(HttpUtil.class);

	public static String postContent(String url, String charset, String[] parameters) {
		HttpURLConnection con = null;
		try {
			con = (HttpURLConnection) new URL(url).openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setConnectTimeout(3000);
			con.setReadTimeout(3000);
			con.setUseCaches(false);
			OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), charset);
			for (int i = 0; i < parameters.length; i++) {
				writer.write(parameters[i]);
				if (i < (parameters.length - 1)) {
					writer.write("&");
				}
			}
			writer.flush();
			writer.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(),
					charset));
			char[] buff = new char[1000];
			int length = -1;
			StringBuilder content = new StringBuilder();
			while ((length = reader.read(buff)) != -1) {
				content.append(buff, 0, length);
			}
			reader.close();
			return content.toString();
		} catch (Exception e) {
			logger.error("", e);
			return null;
		} finally {
			if (con != null)
				con.disconnect();
		}
	}

	public static String getContent(String url, String charset) {
		HttpURLConnection con = null;
		try {
			con = (HttpURLConnection) new URL(url).openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(),
					charset));
			char[] buff = new char[1000];
			int length = -1;
			StringBuilder content = new StringBuilder();
			while ((length = reader.read(buff)) != -1) {
				content.append(buff, 0, length);
			}
			reader.close();
			return content.toString(); 
		} catch (Exception e) {
			logger.error("", e);
			return null;
		} finally {
			if (con != null)
				con.disconnect();
		}
	}

}
